package com.jie.algorithm.utils;

import android.graphics.Color;

public class ColorUtils {

    // 彩虹颜色：红、紫、蓝、靛、绿、黄、橙
    private static final int[] COLORS = new int[]{0xFFFF0000, 0xFFFF00FF,
            0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000};

    /**
     * 微调颜色值
     */
    private static int ave(int s, int d, float p) {
        return s + Math.round(p * (d - s));
    }

    /**
     * 根据算法计算高度和颜色对应值
     * @param ratio 取值 [0 - 1]
     * @return 颜色
     */
    public static int calculateColor(float ratio) {

        if (ratio <= 0) {
            return COLORS[0];
        }
        if (ratio >= 1) {
            return COLORS[COLORS.length - 1];
        }

        float p = ratio * (COLORS.length - 1);
        int i = (int) p;
        p -= i;

        int c0 = COLORS[i];
        int c1 = COLORS[i + 1];
        int a = ave(Color.alpha(c0), Color.alpha(c1), p);
        int r = ave(Color.red(c0), Color.red(c1), p);
        int g = ave(Color.green(c0), Color.green(c1), p);
        int b = ave(Color.blue(c0), Color.blue(c1), p);

        return Color.argb(a, r, g, b);
    }

}
